package cn.gjxblog.validation.mvc.demo1;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * SpringMVC对Controller提供数据校验的原理
 *
 * 对@RequestBody这种类型的入参处理入口  RequestResponseBodyMethodProcessor
 *  先完成数据绑定将HttpServletRequest的请求体的内容绑定到对象的JavaBean中，然后再进行数据校验
 * @see org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor#resolveArgument(org.springframework.core.MethodParameter, org.springframework.web.method.support.ModelAndViewContainer, org.springframework.web.context.request.NativeWebRequest, org.springframework.web.bind.support.WebDataBinderFactory)
 * 校验入口
 * @see org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver#validateIfApplicable(org.springframework.web.bind.WebDataBinder, org.springframework.core.MethodParameter)
 */

@RestController
@RequestMapping
public class HelloController {

    /**
     * SpringMVC中Controller提供@Valid对JavaBean的校验
     *
     * 两点注意
     * 1、@Valid
     * 2、BindingResult
     */
    @PostMapping("/hello")
    public Object helloPost(@Valid @RequestBody Person person, BindingResult result){
        System.out.println(result.getErrorCount());
        System.out.println(result.getAllErrors());
        return person;
    }

    /**
     * 校验异常交给全局异常处理器处理
     *@see cn.gjxblog.validation.mvc.demo1.MethodArgumentNotValidExceptionHandler#handleMethodArgumentNotValid(org.springframework.web.bind.MethodArgumentNotValidException)
     */
    @PostMapping("/hello2")
    public Object helloPost2(@Valid @RequestBody Person person){
        return person;
    }



}
